<?php

class Application_Model_RankingsPage 
{
	protected $_roundSettings = "round_settings";
	protected $_race = "race";
	protected $_class = "hero_class";
	protected $_userStats = "user_stats";
	protected $_lightUserArmy = "light_user_army";
	protected $_darkUserArmy = "dark_user_army";
	
//	SELECT `user_stats`.`user_fk`,`user_stats`.`power`
//FROM `alpha1`.`dark_user_army`, `alpha1`.`light_user_army`, `alpha1`.`user_stats`
//WHERE `dark_user_army`.`user_fk` = `user_stats`.`user_fk` 
//OR `light_user_army`.`user_fk` = `user_stats`.`user_fk` 
//GROUP BY(`user_stats`.`user_fk`)
//ORDER BY `user_stats`.`power` DESC, `user_stats`.`user_fk` ASC;
	
	
	
	public function getRankingsPageList()
    {
    	$db = Zend_Db_Table::getDefaultAdapter();
    	$seletAttackPages = new Zend_Db_Select($db);
    	$seletAttackPages->from(array('da' => $this->_darkUserArmy))
    					 ->from(array('la' => $this->_lightUserArmy))
    					 ->from(array('us' => $this->_userStats))
    					 ->join(array('rs' => $this->_roundSettings), 'us.user_fk = rs.user_fk', array('alias'))
    					 ->join(array('r' => $this->_race), 'rs.race_fk = r.id', array('race_name'=>'name'))
    					 ->where("us.user_fk = la.user_fk OR us.user_fk = da.user_fk ")
    					 ->group('us.user_fk')
    					 ->order('us.power DESC')
    					 ->order('rs.alias ASC');
    	return $seletAttackPages;
 	}

 	
 	
//   	SELECT COUNT(*) 
//		FROM user_stats us, round_settings rs
//		WHERE us.user_fk = rs.user_fk 
//		AND us.POWER > 90;
 	public function getPlayerRank($power, $user_fk)
    {
		$db = Zend_Db_Table::getDefaultAdapter();
		$select = $db->select()
            ->from(array('us' => $this->_userStats))
			->where('us.power >?',$power);
        $result = $db->fetchAll($select);
        
        $rank = count($result);
        
        $select = $db->select()
            ->from(array('us' => $this->_userStats))
            ->join(array('rs' => $this->_roundSettings), 'us.user_fk = rs.user_fk', array('alias'))
			->where('us.power =?',$power)
			->order('rs.alias ASC');
        $result = $db->fetchAll($select);
        $count =  1;

        foreach ( $result as $key => $value)
        {
        	if($value['user_fk'] == $user_fk)
        	{
        		break;
        	}
        	else
        	{ 
        		$count = $count + 1;
        	}
        }
        
        $rank = $rank + $count;
        
    	return $rank;
    	
    }

}

